﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace Sparkle.Lib.Attributes
{
    [global::System.AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)]
    public class ValueNotEqualAttribute : ValidationAttribute
    {
        readonly object _notEqualValue;

        // This is a positional argument
        public ValueNotEqualAttribute(object notEqualValue)
        {
            this._notEqualValue = notEqualValue;
        }

        public object NotEqualValue
        {
            get { return _notEqualValue; }
        }
        #if SILVERLIGHT
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            return base.IsValid(value, validationContext);
        }
#else
        public override bool IsValid(object value)
        {
            if (_notEqualValue == value) // this is for null
            { return true; }

            if ((_notEqualValue != null && value == null) || (_notEqualValue == null && value != null))
            {return true;}

            if(value.GetType().IsGenericType && value is KeyValuePair<string,object>)
            {
                var keyVal = (KeyValuePair<string, object>) value;
                return _notEqualValue.ToString() != keyVal.Value.ToString();

            }
            // check value using ToString
            return  _notEqualValue.ToString() != value.ToString();

        }
#endif
    }
}
